/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.ui.interfaces.OnSyncListener;
import utsc.apps.utschedule.util.TimetableHelper;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

/**
 * This AsyncTask is used to perform a synchronisation of the course timetable
 * from Intranet. It makes a call to our dummy webservice to retrieve the course
 * timetable data.
 * 
 */
public class SyncCourseTask extends AsyncTask<String, Void, ArrayList<Course>> {
	
	private Context _context;
	public SyncCourseTask(Context context){
		this._context=context;
	}
	
	private String _term;
	private ProgressDialog _progressDialog;
	/**
	 * The dummy webservice url we created.
	 */
	private static final String URL="http://utschedule.comoj.com/synccourse.php";
	private static final String PARAM_STRING="userid=%s&password=%s&term=%s";
	
	public SyncCourseTask(Context context, String term) {
		_context=context;
		_term=term;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		_progressDialog=new ProgressDialog(_context);
		_progressDialog.setMessage(_context.getResources().getText(R.string.loading));
		_progressDialog.show();
	}
	
	@Override
	protected ArrayList<Course> doInBackground(String...loginParams) {
		InputStream is = null;
	    try {
	    	String param=String.format(PARAM_STRING, loginParams[0],URLEncoder.encode(loginParams[1],"utf-8"),_term);
	        URL url = new URL(URL);
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setReadTimeout(10000 /* milliseconds */);
	        conn.setConnectTimeout(15000 /* milliseconds */);
	        conn.setDoOutput(true);
	        conn.setRequestMethod("POST");
	        conn.setFixedLengthStreamingMode(param.getBytes().length);
	        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	        //send the POST out
	        PrintWriter out = new PrintWriter(conn.getOutputStream());
	        out.print(param);
	        out.close();
	        // Starts the query
	        conn.connect();
	        int response = conn.getResponseCode();
	        if (response==HttpURLConnection.HTTP_OK) {
	        	is = new BufferedInputStream(conn.getInputStream());
	        	is.mark(1<<24);
	        	if (is.read()==-1) {
	        		if (is!=null) {
	        			is.close();
					}
					return null;
				}else {
					is.reset();
					JsonReader reader=new JsonReader(new InputStreamReader(is,"UTF-8"));
		        	ArrayList<Course> results=new ArrayList<Course>();
		        	reader.beginArray();
		        		while (reader.hasNext()) {
							reader.beginObject();
							Course c=new Course();
							while (reader.hasNext()) {
								String name=reader.nextName();
								if (name.equals("course")&&reader.peek()!=JsonToken.NULL) {
									c.set_courseCode(reader.nextString());
								}else if (name.equals("meeting")&&reader.peek()!=JsonToken.NULL) {
									c.set_section(reader.nextString());
									if (!c.get_section().contains("LEC")) {
										c.set_tutorial(true);
									}
								}else if (name.equals("starttime")&&reader.peek()!=JsonToken.NULL) {
									c.set_startTime(TimetableHelper.convertFromDateTimeStringToMillis(reader.nextString(), TimetableHelper.TYPE_TIME24).getTime());
								}else if (name.equals("endtime")&&reader.peek()!=JsonToken.NULL) {
									c.set_endTime(TimetableHelper.convertFromDateTimeStringToMillis(reader.nextString(), TimetableHelper.TYPE_TIME24).getTime());
								}else if (name.equals("location")&&reader.peek()!=JsonToken.NULL) {
									c.set_location(reader.nextString());
								}else if (name.equals("instructor")&&reader.peek()!=JsonToken.NULL) {
									c.set_instructor(reader.nextString());
								}else if (name.equals("day")&&reader.peek()!=JsonToken.NULL) {
									c.set_day(TimetableHelper.parseSearchDate(reader.nextString()));
								}else {
									reader.skipValue();
								}
							}
							c.set_syncID(c.get_courseCode()+c.get_section()+c.get_day());
							reader.endObject();
							results.add(c);
						}
		        	reader.endArray();
		        	reader.close();
		        	return results;
				}
			}

	        return null;
	        
	    // Makes sure that the InputStream is closed after the app is
	    // finished using it.
	    } catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onPostExecute(ArrayList<Course> result) {
		_progressDialog.dismiss();
		((OnSyncListener<Course>)_context).onSyncCompleted(result);
	}


}
